import os
import subprocess
import sys
import shutil
from pathlib import Path

from venv_manager import list_venvs


# 指定Python安装目录
pythonInstallDir = r"C:\Python"

# 获取所有可用的Python
pythonVersions = [d for d in os.listdir(pythonInstallDir) 
                   if os.path.isdir(os.path.join(pythonInstallDir, d)) and 
                     os.path.exists(os.path.join(pythonInstallDir, d, 'python.exe'))]
 

# 检查是否找到 Python 环境
if not pythonVersions:
    print(f"No Python environments found in {pythonInstallDir}")
    sys.exit(1)
 
# 显示所有可用的 Python 环境
print("Available Python environments:")
for i, version in enumerate(pythonVersions):
    print(f"{i}: {os.path.join(pythonInstallDir, version)}")
 
# 读取用户输入的 Python 环境索引
try:
    selected_index = int(input("Enter the index of the Python environment you want to use: "))
    if selected_index < 0 or selected_index >= len(pythonVersions):
        raise ValueError
except ValueError:
    print("Invalid index")
    sys.exit(1)

# 获取选择的 Python 环境路径
selected_python_path = os.path.join(pythonInstallDir, pythonVersions[selected_index], 'python.exe')
 
# 读取虚拟环境目录名
user_home_dir = Path.home()
venv_base_dir = Path(user_home_dir).joinpath('.venvs')
venv_name = input("Enter the name for the virtual environment: ")
venv_path = venv_base_dir.joinpath(venv_name)

exist_venv_list = list_venvs()
if venv_name in exist_venv_list:
    print(f"Virtual environment {venv_name} already exists.")
    sys.exit(1)

# 创建虚拟环境
try:
    subprocess.run([selected_python_path, '-m', 'venv', str(venv_path)], check=True)
except subprocess.CalledProcessError as e:
    print(f"Failed to create virtual environment: {e}")
    sys.exit(1)

batch_dir = Path(r'C:\create_venv')
quick_activate_script_path = batch_dir.joinpath(f"{venv_name}-activate.bat")
print(f"quick_activate_script_path: {quick_activate_script_path}")

quick_activate_script_content = f"""
@echo off
REM Quick activation script for the virtual environment
REM Generated by Python script
 
set venvPath={venv_path}
if exist "%venvPath%\\Scripts\\activate.bat" (
    call "%venvPath%\\Scripts\\activate.bat"
) else (
    echo Virtual environment not found or activate script is missing
    color 0C
)
"""

# 将内容写入快速激活脚本
quick_activate_script_path.write_text(quick_activate_script_content)

print(f"Virtual environment created at: {venv_path}")
print(f"Quick activation script created at: {quick_activate_script_path}")
print(f"To activate the virtual environment in Command Prompt, run: {quick_activate_script_path.name}")
